Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Difference between if (array.length > 0) and if (array?.length) in Javascript (Why is array.length > 0 falsey?)

I'm a super green developer that started my first job last week. I got a comment from another developer to add a condition to check if array is undefined and to check if array is in fact an array.

Initially I used:

$: hasActiveCoupons = $cart.coupons && $cart.coupons.length > 0;

if (hasActiveCoupons && $cart.coupons.find((coupon) => coupon.id === couponCode)) {
...
}

But then she pointed out to me that $cart.coupons.length > 0 would return a falsey value. And corrected it by writing:

if ($cart.coupons?.length && $cart.coupons.find((coupon) => coupon.id === couponCode)) {
...
}

So I am wondering how this works? I tired reading a few other questions but I don't fully grasp this concept.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

$cart.coupons.length > 0 will return a falsey value if coupons is empty, but there is no need to check length this way in this case. A smaller approach to this flow would be the following:

$cart.coupons?.find(({ id }) => id === couponCode);

If coupons is undefined, undefined is returned.

If no values satisfy the testing function inside find, undefined is returned.

Therefore, no need to test length separately.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda